<?php

namespace App\Http\Controllers\User;

use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\DB;
use App\Models\CommonModel;
use App\Models\UserModel;
use App\Models\HomeModel;
use Illuminate\Http\Request;
use App\Libary\Captcha\Code;
use Storage;

// require_once '../app/libary/captcha/Code.class.php';

class IndexController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Login Controller
    |--------------------------------------------------------------------------
    |
    | This controller handles authenticating users for the application and
    | redirecting them to your home screen. The controller uses a trait
    | to conveniently provide its functionality to your applications.
    |
    */

    use AuthenticatesUsers;

    /**
     * Where to redirect users after login.
     *
     * @var string
     */
    protected $redirectTo = '/user/index';
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct(){
        $type_id = 6;
        // $global = UserModel::getGlobalVal();
        // $menu = UserModel::getMenu();
        // view()->share(['global'=> $global,'menu'=>$menu,'type_id'=>$type_id]);
    }

    // 訂單type,0待支付，1已付款，2已完成，3默認全部
    public function index($type=3){
        $uid = session('user')->id;
        if($type==3){
            $list = UserModel::getOrderList($uid);
        }elseif($type>=0 && $type<=2){
            $list = UserModel::getOrderList($uid,$type);
        }else{
            $type=3;
            $list = UserModel::getOrderList($uid);
        }
        // dd($list);
        return view('user/index/index',['list'=>$list,'type'=>$type]);
    }
    // 完善資料
    public function setInf(){
        $uid = session('user')->id;
        // dd(session('user'));
        return view('user/index/setInf');
    }
    public function doSetInf(Request $request){
        if($request->isMethod('POST')){
            $uid = session('user')->id;
            $data = $request->input();
            if(empty($data['user_phone']) || empty($data['bank_name']) || empty($data['bank_num']) || empty($data['bank_owner']) || empty($data['bank_owner']) || empty($data['idcard'])){
                return json_encode(['res' => 0, 'msg'=>'帶“*”號項不能為空']);
            }
            // dd($data);
            $file = $request->file('idcard_img');
            // dd($file);
            if(!$file){
                return json_encode(['res' => 0, 'msg'=>'請上傳證件照片！']);
            }
            if($file!=null){
                if ($file->isValid()) {
                    // 獲取文件相關信息
                    $originalName = $file->getClientOriginalName(); // 文件原名
                    $ext = $file->getClientOriginalExtension();     // 擴展名
                    $imagesType = ['jpg','jpeg','gif','bmp','png'];
                    if(!in_array($ext,$imagesType)){
                        return response()->json(array('res' => 0,'msg'=>'不允許上傳的文件類型'));
                    }
                    $size=$file->getSize();
                    if($size>2*1024*1024){
                        return response()->json(array('res' => 0,'msg'=>'文件過大，推薦圖片大小：2M'));
                    }
                    $realPath = $file->getRealPath();   //臨時文件的絕對路徑
                    $type = $file->getClientMimeType();     // image/jpeg
                    // 上傳文件
                    $filename = date('YmdHis') . '-' . uniqid() . '.' . $ext;

                    $uploaddirs = '/uploads/user/'; //圖片路徑
                    $path = date("Y-m-d", time());  //獲取當前時間
                    $uploaddir = $uploaddirs . $path . '/';
                    $user['idcard_img'] = $uploaddir.$filename;
                    // 使用我們新建的uploads本地存儲空間（目錄）
                    $bool = Storage::disk('user')->put($filename, file_get_contents($realPath));
                    if($bool!=true){
                        $arrJson = array('res' => 0, 'msg'=>'圖片上傳失敗');
                        return json_encode($arrJson);
                    }
                }
            }
            $pwd=$data['pay_pass'];
            $repwd=$data['re_pay_pass'];
            if($pwd==$repwd){
                $user['trade_pass'] = md5(base64_encode($pwd));
            }else{
                $arrJson = array('res' => 0, 'msg'=>'兩次輸入的交易密碼不相同');
            }

            $user['family']=trim($data['family']);
            $user['name']=trim($data['name']);
            // $user['sex']=$data['sex'];
            // $user['idcard_time']=trim($data['idcard_time']);
            if(strpos($user['idcard_time'], '_')){
                return json_encode(['res' => 0, 'msg'=>'請將證件簽署日期填寫完整！']);
            }
            $user['birthday']=trim($data['birthday']);
            if(strpos($user['birthday'], '_')){
                return json_encode(['res' => 0, 'msg'=>'請將證件簽署日期填寫完整！']);
            }
            // $user['address']=trim($data['address']);
            $user['user_phone']=$data['user_phone'];
            $user['bank_name']=trim($data['bank_name']);
            $user['bank_num']=trim($data['bank_num']);
            // $user['bank_address']=trim($data['bank_address']);
            $user['bank_owner']=trim($data['bank_owner']);
            $user['idcard']=trim($data['idcard']);
            $save = UserModel::updateUser($uid,$user);
            if($save == true){
                UserModel::updateUser($uid,['status'=>1]);
                $userInfo = HomeModel::getOneUser(['id'=>$uid]);
                session(['user'=>$userInfo]);
                $arrJson = array('res' => 1, 'msg'=>'資料提交成功','jumpUrl'=>$this->redirectTo);
            }else{
                $arrJson = array('res' => 0, 'msg'=>'資料提交失敗');
            }
            return json_encode($arrJson);
        }
    }
    // 修改資料：1修改資料，2修改登錄密碼，3修改交易密碼
    public function editInf($type=1){
        $uid = session('user')->id;
        $user = UserModel::getOneUser(['id'=>$uid]);
        // dd($user);
        return view('user/index/editInf',['type'=>$type,'user'=>$user]);
    }
    public function doEditInf(Request $request){
        if($request->isMethod('POST')){
            $uid = session('user')->id;
            $data = $request->input();
            if(empty($data['user_phone']) || empty($data['bank_name']) || empty($data['bank_num']) || empty($data['bank_owner']) || empty($data['bank_owner']) || empty($data['idcard'])){
                return json_encode(['res' => 0, 'msg'=>'帶“*”號項不能為空']);
            }
            $file = $request->file('idcard_img');
            // dd($file);
            if($file!=null){
                if ($file->isValid()) {
                    // 獲取文件相關信息
                    $originalName = $file->getClientOriginalName(); // 文件原名
                    $ext = $file->getClientOriginalExtension();     // 擴展名
                    $imagesType = ['jpg','jpeg','gif','bmp','png'];
                    if(!in_array($ext,$imagesType)){
                        return response()->json(array('res' => 0,'msg'=>'不允許上傳的文件類型'));
                    }
                    $size=$file->getSize();
                    if($size>2*1024*1024){
                        return response()->json(array('res' => 0,'msg'=>'文件過大，推薦圖片大小：2M'));
                    }
                    $realPath = $file->getRealPath();   //臨時文件的絕對路徑
                    $type = $file->getClientMimeType();     // image/jpeg
                    // 上傳文件
                    $filename = date('YmdHis') . '-' . uniqid() . '.' . $ext;

                    $uploaddirs = '/uploads/user/'; //圖片路徑
                    $path = date("Y-m-d", time());  //獲取當前時間
                    $uploaddir = $uploaddirs . $path . '/';
                    $user['idcard_img'] = $uploaddir.$filename;
                    // 使用我們新建的uploads本地存儲空間（目錄）
                    $bool = Storage::disk('user')->put($filename, file_get_contents($realPath));
                    if($bool!=true){
                        $arrJson = array('res' => 0, 'msg'=>'圖片上傳失敗');
                        return json_encode($arrJson);
                    }else{
                        if( !empty(session('user')->idcard_img) || !file_exists(session('user')->idcard_img) ){
                            @unlink(public_path() . session('user')->idcard_img);
                        }
                    }
                }
            }
            // dd($data);
            $user['family']=trim($data['family']);
            $user['name']=trim($data['name']);
            // $user['sex']=$data['sex'];
            // $user['birthday']=trim($data['birthday']);
            // $user['address']=trim($data['address']);
            $user['user_phone']=$data['user_phone'];
            // $user['bank_address']=trim($data['bank_address']);
            $user['bank_name']=trim($data['bank_name']);
            $user['bank_num']=trim($data['bank_num']);
            $user['bank_owner']=trim($data['bank_owner']);
            $user['idcard']=trim($data['idcard']);
            $save = UserModel::updateUser($uid,$user);
            if($save == true || $bool==true){
                $userInfo = HomeModel::getOneUser(['id'=>$uid]);
                session(['user'=>$userInfo]);
                $arrJson = array('res' => 1, 'msg'=>'資料修改成功','jumpUrl'=>$this->redirectTo);
            }else{
                $arrJson = array('res' => 0, 'msg'=>'修改失敗');
            }
            return json_encode($arrJson);
        }
    }
    // 修改登錄密碼
    public function doEditPass(){
        if($request->isMethod('POST')){
            $uid = session('user')->id;
            $data = $request->input();
            // dd($data);
            $user_pass=$data['user_pass'];
            $new_pass=$data['new_pass'];
            $new_repass=$data['new_repass'];
            if($new_pass!=$new_repass){
                return response()->json(['res'=>'0','msg'=>'兩次輸入的新密碼不壹致，請重新輸入！']);
            }
            if( session('user')->user_pass!=md5(base64_encode(trim($data['user_pass']))) ){
                return response()->json(['res'=>'0','msg'=>'當前密碼錯誤，請重新輸入！']);
            }else{
                $newpass = base64_encode(trim($data['new_pass']));
                $save = UserModel::updateUser($uid,['user_pass'=>$newpass]);
                if($save){
                    $userInfo = HomeModel::getOneUser(['id'=>$uid]);
                    session(['user'=>$userInfo]);
                    return response()->json(['res'=>'1','msg'=>'修改成功！','jumpUrl'=>'/user/editInf']);
                }else{
                    return response()->json(['res'=>'0','msg'=>'修改失敗！']);
                }
            }
        }else{
            return response()->json(['res'=>'0','msg'=>'提交失敗！']);
        }
    }
    // 修改交易密碼
    public function doEditTradePass(){
        if($request->isMethod('POST')){
            $uid = session('user')->id;
            $data = $request->input();
            // dd($data);e            
            $trade_pass=$data['trade_pass'];
            $new_pass=$data['new_pass'];
            $new_repass=$data['new_repass'];
            if($new_pass!=$new_repass){
                return response()->json(['res'=>'0','msg'=>'兩次輸入的新交易密碼不壹致，請重新輸入！']);
            }
            if( session('user')->trade_pass!=md5(base64_encode(trim($data['trade_pass']))) ){
                return response()->json(['res'=>'0','msg'=>'當前輸入的交易密碼錯誤，請重新輸入！']);
            }else{
                $newpass = base64_encode(trim($data['new_pass']));
                $save = UserModel::updateUser($uid,['trade_pass'=>$newpass]);
                if($save){
                    $userInfo = HomeModel::getOneUser(['id'=>$uid]);
                    session(['user'=>$userInfo]);
                    return response()->json(['res'=>'1','msg'=>'修改成功！','jumpUrl'=>'/user/editInf']);
                }else{
                    return response()->json(['res'=>'0','msg'=>'修改失敗！']);
                }
            }
        }else{
            return response()->json(['res'=>'0','msg'=>'提交失敗！']);
        }
    }
    // 資金
    public function money($type=1){
        $uid = session('user')->id;
        $money = UserModel::getMoney($uid);
        $user = UserModel::getOneUser(['id'=>$uid]);
        // dd($money);
        return view('user/index/money',['type'=>$type,'money'=>$money,'user'=>$user]);
    }

    // 確認購買頁面
    public function playTure($id){
        // dd(session('user')->user_phone);
        // dd($id);
        $uid = session('user')->id;
        $orders = CommonModel::getField('order','id',['uid'=>$uid]);
        $res = $orders->toArray();
        // dd($res);
        if(in_array($id,$res)){
            $order = UserModel::getOneOrder($id);
            // dd($order);
            $product = HomeModel::getProduct(['weight','price'],['id'=>$order->pid]);
            // dd($product);
            $image = HomeModel::getImage(['id','img_url'],['status'=>0,'pid'=>$order->pid]);
            // dd($image);
            return view('user/index/playTure',['order'=>$order,'product'=>$product,'image'=>$image,'user_phone'=>session('user')->user_phone]);
        }else{
            return redirect('/msg')->with(['res'=>0,'msg'=>'訂單錯誤','url'=>'/']);
        }
        
    }
    // 確認購買
    public function doPlayTure(Request $request){
        if($request->input()){
            $uid = session('user')->id;
            $data = $request->input();
            // dd($data);
            $id =  intval($data['id']);
            if(trim($data['info'])!=''){
                $order['info'] =  trim($data['info']);
            }
            
            $order['phone'] = trim($data['phone']);
            $order['status'] = 1;
            if(!is_phone(trim($data['phone']))){
                return response()->json(['res'=>'0','msg'=>'手機號碼不正確，請重新輸入！']);
            }
            $userInfo = HomeModel::getOneUser(['id'=>$uid]);
            // dd($userInfo);
            if( $userInfo->trade_pass!=md5(base64_encode(trim($data['trade_pass']))) ){
                return response()->json(['res'=>'0','msg'=>'交易密碼輸入不正確，請重新輸入！']);
            }else{
                $orderInfo = UserModel::getOneOrder($id);
                if($userInfo->account_money<$orderInfo->money){
                    return response()->json(['res'=>'0','msg'=>'余額不足，請充值']);
                }
                userMoneyLog($uid,1,$orderInfo->money, $orderInfo->id, '支付保證金,待取貨');
                // DB::connection()->enableQueryLog(); // 開啟查詢日誌
                $save = CommonModel::updateData('order',['id'=>$id],$order);
                // $queries = DB::getQueryLog(); // 獲取查詢日誌
                // dd($save);
                // print_r($queries);exit; // 即可查看執行的sql，傳入的慘數等等
                if($save==1){
                    return response()->json(['res'=>'1','msg'=>'提交成功！','jumpUrl'=>'/user/index']);
                }else{
                    return response()->json(['res'=>'0','msg'=>'提交失敗！']);
                }
            }
        }
    }
    // 提交充值證明
    public function doRemit(Request $request){
        if($request->input()){
            $uid = session('user')->id;
            $data = $request->input();
            $file = $request->file('receipt_img');
            // 判斷收據號碼是否重復，充值證明是否重復提交
            $count = CommonModel::getCount('recharge',['receipt_num'=>trim($data['receipt_num'])]);
            if($count>0){
                return json_encode(['res' => 0, 'msg'=>'您本次充值證明已近提交，不能重復提交']);
            }
            if(!$file){
                return json_encode(['res' => 0, 'msg'=>'請上傳證件照片！']);
            }
            if($file!=null){
                if ($file->isValid()) {
                    // 獲取文件相關信息
                    $originalName = $file->getClientOriginalName(); // 文件原名
                    $ext = $file->getClientOriginalExtension();     // 擴展名
                    $imagesType = ['jpg','jpeg','gif','bmp','png'];
                    if(!in_array($ext,$imagesType)){
                        return response()->json(array('res' => 0,'msg'=>'不允許上傳的文件類型'));
                    }
                    $size=$file->getSize();
                    if($size>2*1024*1024){
                        return response()->json(array('res' => 0,'msg'=>'文件過大，推薦圖片大小：2M'));
                    }
                    $realPath = $file->getRealPath();   //臨時文件的絕對路徑
                    $type = $file->getClientMimeType();     // image/jpeg
                    // 上傳文件
                    $filename = date('YmdHis') . '-' . uniqid() . '.' . $ext;

                    $uploaddirs = '/uploads/user/'; //圖片路徑
                    $path = date("Y-m-d", time());  //獲取當前時間
                    $uploaddir = $uploaddirs . $path . '/';
                    $recharge['receipt_img'] = $uploaddir.$filename;
                    // 使用我們新建的uploads本地存儲空間（目錄）
                    $bool = Storage::disk('user')->put($filename, file_get_contents($realPath));
                    if($bool!=true){
                        $arrJson = array('res' => 0, 'msg'=>'圖片上傳失敗');
                        return json_encode($arrJson);
                    }
                }
            }
            $recharge['uid'] = $uid;
            $recharge['money'] = floatval($data['money']);
            $recharge['bank_id'] = intval($data['bank_id']);
            $recharge['remit_type'] = intval($data['remit_type']);
            $recharge['remit_day'] = trim($data['remit_day']);
            $recharge['receipt_num'] = trim($data['receipt_num']);
            $recharge['add_time'] = time();
            $add = CommonModel::addDataGetId('recharge',$recharge);
            if($add){
                return json_encode(['res' => 1, 'msg'=>'提交成功','jumpUrl'=>'/user/money']);
            }else{
                return json_encode(['res' => 0, 'msg'=>'提交失敗']);
            }
            
        }
    }
    // 提現
    public function doWithdraw(Request $request){
        if($request->input()){
            $uid = session('user')->id;
            $data = $request->input();
            // 判斷該用護是否已經存在未處理的提現申請
            $count = CommonModel::getCount('withdraw',['uid'=>$uid,'status'=>0]);
            if($count>0){
                return json_encode(['res' => 0, 'msg'=>'您已有未處理的提現申請']);
            }
            $moneyInfo = UserModel::getMoney($uid);
            $withdraw['uid'] = $uid;
            $withdraw['bank_owner'] = trim($data['bank_owner']);
            $withdraw['bank_num'] = trim($data['bank_num']);
            $withdraw['bank_name'] = trim($data['bank_name']);
            $withdraw['money'] = floatval($data['money']);
            $withdraw['add_time'] = time();
            if($withdraw['money']>($moneyInfo->account_money)){
                return json_encode(['status' => 0, 'message'=>'余額不足']);
            }
            $add = CommonModel::addDataGetId('withdraw',$withdraw);
            if($add){
                userMoneyLog($uid, 4, $withdraw['money'], 0, '用護申請提現');
                return json_encode(['res' => 1, 'msg'=>'提交成功','jumpUrl'=>'/user/money']);
            }else{
                return json_encode(['res' => 0, 'msg'=>'提交失敗']);
            }
        }
    }



}
